package com.example.java_gobang.api;

import com.example.java_gobang.game.OnlineUserManager;
import com.example.java_gobang.game.RoomManager;
import com.example.java_gobang.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Slf4j
@Component
public class AIGameAPI extends TextWebSocketHandler {
    @Autowired
    private RoomManager roomManager;

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private UserMapper userMapper;

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("进入AI房间");
        GameReadyResponse gameReadyResponse = new GameReadyResponse();
        User user = (User) session.getAttributes().get("user");
        if (user == null) {
            gameReadyResponse.setOk(false);
            gameReadyResponse.setReason("用户未登录！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsBytes(gameReadyResponse)));
            session.close();
            return;
        }
        Room room = roomManager.getRoomByUserId(user.getUserId());
        if (room == null) {
            gameReadyResponse.setOk(false);
            gameReadyResponse.setReason("用户未匹配到!");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameReadyResponse)));
            return;
        }
        if (onlineUserManager.getFromGameHall(user.getUserId()) != null || onlineUserManager.getFromGameRoom(user.getUserId()) != null) {
            gameReadyResponse.setOk(true);
            gameReadyResponse.setReason("禁止一个账号多开游戏页面!");
            gameReadyResponse.setMessage("repeatConnection");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameReadyResponse)));
            session.close();
            return;
        }
        onlineUserManager.enterGameRoom(user.getUserId(), session);
        //服务器通知玩家，游戏双方已经准备就绪
        noticeGameReady(room, room.getUser1(), room.getUser2());
    }
    private void noticeGameReady(Room room, User thisUser, User thatUser) throws IOException {
        GameReadyResponse gameReadyResponse = new GameReadyResponse();
        gameReadyResponse.setOk(true);
        gameReadyResponse.setReason("");
        gameReadyResponse.setMessage("gameReady");
        gameReadyResponse.setRoomId(room.getRoomId());
        gameReadyResponse.setThisUserId(thisUser.getUserId());
        gameReadyResponse.setThatUserId(thatUser.getUserId());
        gameReadyResponse.setWhiteUser(room.getWhiteUserId());
        gameReadyResponse.setThatUserName(thatUser.getUsername());
        WebSocketSession webSocketSession = onlineUserManager.getFromGameRoom(thisUser.getUserId());
        webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(gameReadyResponse)));
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        User user = (User) session.getAttributes().get("user");
        Room room = roomManager.getRoomByUserId(user.getUserId());
        String payload = (String) message.getPayload();
        GameRequest gameRequest = objectMapper.readValue(payload, GameRequest.class);
        room.putChess(gameRequest);
        room.AImove();
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User user = (User) session.getAttributes().get("user");
        WebSocketSession webSocketSession = onlineUserManager.getFromGameRoom(user.getUserId());
        if (webSocketSession == session) {
            log.info("玩家id :" + user.getUserId() + "异常");
            onlineUserManager.exitGameRoom(user.getUserId());
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = (User) session.getAttributes().get("user");
        WebSocketSession webSocketSession = onlineUserManager.getFromGameRoom(user.getUserId());
        if (webSocketSession == session) {
            log.info("玩家id :" + user.getUserId() + "掉线");
            onlineUserManager.exitGameRoom(user.getUserId());
        }
    }
}
